﻿using System.Net;
using Automatic_Campus_Net.Model;
using RestSharp;
using RestSharp.Authenticators;

namespace AutoInternet.Utils;

public class HttpUtils
{
    private static RestClient? _client;

    public static RequestModel _RequestModel;

    public static void SetRequestModel(RequestModel requestModel)
    {
        _RequestModel = requestModel;
    }

    public static T? Get<T>(String resource)
    {
        RestRequest request = new RestRequest(resource);
        RestResponse restResponse = GetClinet().Execute(request);
        if (restResponse.Content != null)
        {
            string jsonResult = GetJsonResult(restResponse.Content);
            T? deserializeObject = JsonUtil.DeserializeObject<T>(jsonResult);
            return deserializeObject;
        }
        else
        {
            return default;
        }
    }

    private static RestClient GetClinet()
    {
        if (_client == null)
        {
            _client = new RestClient(_RequestModel.Host);
            _client.Options.MaxTimeout = _RequestModel.MaxTimeOut * 1000;
            _client.Options.ThrowOnAnyError = false;
            _client.Options.FailOnDeserializationError = false;
            _client.Options.ThrowOnAnyError = false;
            _client.Options.ThrowOnDeserializationError = false;
        }

        return _client;
    }

    public static String GetJsonResult(String data)
    {
        int indexOf = data.IndexOf('(');
        int lastIndexOf = data.LastIndexOf(')');
        return data.Substring(indexOf + 1, lastIndexOf - indexOf - 1);
    }
}